public class SetZeroes {
    // leetcode 矩阵置零
    // https://leetcode.cn/problems/set-matrix-zeroes/description/?envType=study-plan-v2&envId=top-100-liked
    public void setZeroes(int[][] matrix) {
        // flg1记录第一行是否存在0，flg2记录第一列是否存在0
        boolean flg1 = false, flg2 = false;
        for (int j = 0; j < matrix[0].length; j++) {
            if (matrix[0][j] == 0) flg1 = true;
        }
        for (int i = 0; i < matrix.length; i++) {
            if (matrix[i][0] == 0) flg2 = true;
        }
        for (int i = 1; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }
        for (int i = 1; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (flg1) {
            for (int j = 0; j < matrix[0].length; j++) {
                matrix[0][j] = 0;
            }
        }
        if (flg2) {
            for (int i = 0; i < matrix.length; i++) {
                matrix[i][0] = 0;
            }
        }
    }
}
